import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/user_group/user_union_detail_model.dart';
import 'package:yysk_app/model/user_group/user_union_member_list_model.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/empty_widget.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:yysk_app/widget/refresh_and_scroll_widget.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/net/http.dart';

class MyGroupListPage extends StatefulWidget {
  static const path = '/MyGroupListPage';
  const MyGroupListPage({super.key});
  @override
  State<StatefulWidget> createState() => _MyGroupListPage();
}

class _MyGroupListPage extends State<MyGroupListPage> {
  final ScrollController scrollController = ScrollController();
  final GlobalController globalController = Get.find();

  var pageNo = 1;
  var pageSize = 20;
  final list = RxList<UnionMemberListModelItem>([]);
  final userUnionDetail = Rx<UserUnionDetailModel?>(null);
  final pointsId = RxString('0');
  final amount = RxString('993.25');
  final pointsName = RxString('积分');
  final pointsImageUrl = RxString('');
  final total = RxInt(0);

  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        getUserUnionMemberList(loadMore: true);
      }
    });
    _handleRefresh();
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
  }

  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    return Scaffold(
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: ImageAssetWidget(
              width: 375.px,
              height: 812.px,
              imageUrl: 'static/images/bg.png',
            ),
          ),
          Column(
            children: [
              Expanded(
                child: Obx(
                  () => Stack(
                    children: [
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: top),
                          CustomAppBar2(title: '我的星盟', context: context),
                          userUnionDetail.value != null
                              ? hiSpace(height: 20.px)
                              : SizedBox(),
                          userUnionDetail.value != null
                              ? Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Container(
                                        width: 200.px,
                                        padding: EdgeInsets.only(left: 32.px),
                                        child: Text(
                                          '${userUnionDetail.value?.unionName}',
                                          style: TextStyle(
                                            fontSize: 20.px,
                                            color: AppColors.fontColor,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      ),
                                      hiSpace(height: 14.px),
                                      Container(
                                        width: 200.px,
                                        padding: EdgeInsets.only(left: 32.px),
                                        child: Text(
                                          '编号：${userUnionDetail.value?.id}',
                                          style: TextStyle(
                                            fontSize: 12.px,
                                            color: AppColors.fontColorGray99,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      ),
                                      hiSpace(height: 3.px),
                                      Container(
                                        width: 200.px,
                                        padding: EdgeInsets.only(left: 32.px),
                                        child: Text(
                                          '建于：${userUnionDetail.value?.createTime}',
                                          style: TextStyle(
                                            fontSize: 12.px,
                                            color: AppColors.fontColorGray99,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      ),
                                      hiSpace(height: 22.px),
                                    ],
                                  ),
                                ],
                              )
                              : SizedBox(),

                          userUnionDetail.value != null
                              ? Container(
                                width: context.width,
                                padding: EdgeInsets.all(16.px),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(18.px),
                                    topRight: Radius.circular(18.px),
                                  ),
                                  gradient: LinearGradient(
                                    colors: [
                                      Color.fromRGBO(31, 33, 38, 1),
                                      Color.fromRGBO(30, 33, 38, 0),
                                    ],
                                    begin: Alignment.topCenter,
                                    end: Alignment.bottomCenter,
                                  ),
                                ),
                                child: Text(
                                  '星盟成员（${total.value + 1}人）',
                                  style: TextStyle(
                                    fontSize: 16.px,
                                    color: AppColors.fontColor,
                                  ),
                                  textAlign: TextAlign.left,
                                ),
                              )
                              : SizedBox(),
                          userUnionDetail.value != null
                              ? Padding(
                                padding: EdgeInsets.only(
                                  left: 12.px,
                                  right: 12.px,
                                ),
                                child: _listItem(
                                  item: userUnionDetail.value?.currentUser,
                                  type: 'myself',
                                ),
                              )
                              : SizedBox(),
                          userUnionDetail.value != null
                              ? Padding(
                                padding: EdgeInsets.only(
                                  left: 12.px,
                                  right: 12.px,
                                ),
                                child: _listItem(
                                  item: userUnionDetail.value?.unionPresident,
                                  type: 'president',
                                ),
                              )
                              : SizedBox(),
                          list.isNotEmpty
                              ? Expanded(
                                child: Container(
                                  padding: EdgeInsets.fromLTRB(
                                    12.px,
                                    0.px,
                                    12.px,
                                    0,
                                  ),
                                  child: RefreshAndScrollWidget(
                                    onRefresh: _handleRefresh,
                                    scrollController: scrollController,
                                    itemBuilder:
                                        (item, index) => _listItem(item: item),
                                    itemCount: list.length,
                                    items: list,
                                    emptyText: '未加入星盟~',
                                  ),
                                ),
                              )
                              : SizedBox(),
                          list.isEmpty && userUnionDetail.value == null
                              ? EmptyWidget()
                              : SizedBox(),
                        ],
                      ),
                      userUnionDetail.value != null
                          ? Positioned(
                            top: 90.px,
                            right: 0.px,
                            child: ImageAssetWidget(
                              imageUrl: 'static/images/mine/group_bg.png',
                              width: 210,
                              height: 165,
                            ),
                          )
                          : SizedBox(),
                      userUnionDetail.value != null
                          ? Positioned(
                            top: 58.px,
                            right: 12.px,
                            child: ImageAssetWidget(
                              imageUrl: 'static/images/mine/group.png',
                              width: 165,
                              height: 165,
                            ),
                          )
                          : SizedBox(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _handleRefresh() async {
    // 获取数据
    getUserUnion();
    getUserUnionMemberList();
  }

  getUserUnion() {
    http.netFetch<UserUnionDetailModel>(
      ApiUrl.getUserUnion,
      params: {},
      method: Method.post,
      success: (result) {
        userUnionDetail.value = result.data;
      },
    );
  }

  getUserUnionMemberList({loadMore = false}) {
    if (loadMore) {
      pageNo++;
    } else {
      pageNo = 1;
    }

    try {
      http.netFetch<UnionMemberListModel>(
        ApiUrl.getPageUnionMember,
        params: {'pageNo': pageNo, 'pageSize': 20},
        method: Method.post,
        success: (result) {
          List<UnionMemberListModelItem> items = result.data?.list ?? [];
          if (loadMore && items.isEmpty) {
            pageNo--;
          }
          if (!loadMore) {
            list.clear();
          }
          list.addAll(items);
          total.value = result.data!.total!;
        },
      );
    } catch (e) {
      if (loadMore) {
        pageNo--;
      }
    }
  }

  _listItem({required item, type}) {
    return Container(
      padding: EdgeInsets.all(10.px),
      margin: EdgeInsets.only(bottom: 8.px),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.px),
        border: Border.all(color: AppColors.backgroundColor.withOpacity(0.1)),
        color: AppColors.backgroundColorBlackLight,
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  LazyImage(
                    imageUrl: '${item.avatarImg}',
                    width: 24.px,
                    height: 24.px,
                    boxFit: BoxFit.cover,
                    borderRadius: 24.px,
                  ),
                  hiSpace(width: 10.px),
                  SizedBox(
                    width: 170.px,
                    child: RichText(
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      text: TextSpan(
                        children: <TextSpan>[
                          TextSpan(
                            text: '${item.nickName}',
                            style: TextStyle(
                              color: AppColors.fontColor,
                              fontSize: 12.px,
                            ),
                          ),
                          TextSpan(
                            text:
                                ' (${item.mobile.substring(item.mobile.length - 4)})',
                            style: TextStyle(
                              color: AppColors.fontColorGray99,
                              fontSize: 12.px,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              type == 'myself' || type == 'president'
                  ? Container(
                    width: 32.px,
                    height: 18.px,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(2.px),
                      gradient: LinearGradient(
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        colors:
                            type == 'myself'
                                ? [
                                  AppColors.fontColorStart00,
                                  AppColors.fontColorEnd00,
                                ]
                                : [AppColors.fontColor, AppColors.fontColor],
                      ),
                    ),
                    child: Center(
                      child: Text(
                        type == 'myself' ? '自己' : '盟主',
                        style: TextStyle(
                          fontSize: 12.px,
                          color: AppColors.fontColorBlack12,
                        ),
                      ),
                    ),
                  )
                  : SizedBox(),
            ],
          ),

          hiSpace(height: 10.px),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                padding: EdgeInsets.only(left: 34.px),
                width: 120.px,
                child: Text(
                  'ID：${item.showId}',
                  style: TextStyle(
                    color: AppColors.fontColorGray99,
                    fontSize: 12.px,
                    overflow: TextOverflow.ellipsis,
                  ),
                  textAlign: TextAlign.left,
                ),
              ),
              Text(
                '入会时间:${item.createTime}',
                style: TextStyle(
                  color: AppColors.fontColorGray99,
                  fontSize: 12.px,
                  overflow: TextOverflow.ellipsis,
                ),
                textAlign: TextAlign.right,
              ),
            ],
          ),
        ],
      ),
    );
  }
}
